{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# How to solve the [Hardest Logic Puzzle Ever](https://en.wikipedia.org/wiki/The_Hardest_Logic_Puzzle_Ever) programmatically.\n",
    "> Three gods A, B, and C are called, in no particular order, True, False, and Random. True always speaks truly, False always speaks falsely, but whether Random speaks truly or falsely is a completely random matter. Your task is to determine the identities of A, B, and C by asking three yes-no questions; each question must be put to exactly one god. The gods understand English, but will answer all questions in their own language, in which the words for yes and no are `da` and `ja`, in some order. You do not know which word means which.\n",
    "\n",
    "With 3 binary questions, it's possible to distinguish $2^3 = 8$ scenarios. And there are $3! = 6$ possibilities. Note that means it's impossible to additionally identify what `da` and `ja` mean, as that would be $3! * 2 = 12$ possibilities.\n",
    "\n",
    "As always, start with modeling the data. We need a ternary enumeration for the god identifiers. It's almost a boolean anyway, so let's use `None` to indicate neither, i.e., Random. To represent the identities, a mapping from names to ids would be natural. But the mapping has to be one-to-one and onto, and using an immutable key is convenient, so an implicitly ordered tuple of names is also a valid choice. Here a named tuple represents the \"state\" of the world ."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "[State(names='ABC', yes='da'),\n",
       " State(names='ABC', yes='ja'),\n",
       " State(names='ACB', yes='da'),\n",
       " State(names='ACB', yes='ja'),\n",
       " State(names='BAC', yes='da'),\n",
       " State(names='BAC', yes='ja'),\n",
       " State(names='BCA', yes='da'),\n",
       " State(names='BCA', yes='ja'),\n",
       " State(names='CAB', yes='da'),\n",
       " State(names='CAB', yes='ja'),\n",
       " State(names='CBA', yes='da'),\n",
       " State(names='CBA', yes='ja')]"
      ]
     },
     "metadata": {},
     "execution_count": 1
    }
   ],
   "source": [
    "import itertools\n",
    "from typing import NamedTuple\n",
    "\n",
    "IDS = (False, True, None)\n",
    "NAMES = 'ABC'\n",
    "WORDS = ('da', 'ja')\n",
    "\n",
    "class State(NamedTuple):\n",
    "    names: str  # order corresponds to IDS\n",
    "    yes: str\n",
    "\n",
    "STATES = list(itertools.starmap(State, itertools.product(map(''.join, itertools.permutations(NAMES)), WORDS)))\n",
    "STATES"
   ]
  },
  {
   "source": [
    "Now to model asking a question. A typical approach would take input parameters relevant to the question, such as asking a god which one they are. And the current reality would be need to be encapsulated to answer the question."
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "source": [
    "def ask(self: State, name: str, id) -> str:\n",
    "    \"\"\"Ask `name`: are you `id`?\"\"\""
   ],
   "cell_type": "code",
   "metadata": {},
   "execution_count": 2,
   "outputs": []
  },
  {
   "source": [
    "The problem with that approach is Random's answer would have to be modeled as actually random, which would require running many simulations. Since this is a logic puzzle, it's easier to model Random's answer as non-deterministic, i.e., could answer either way. The question will take as input the current set of possible states, splitting the states into two groups corresponding to answers da or ja. This function will be used in a search algorithm anyway, so it's effectively participating in the search."
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "source": [
    "def ask(name: str, id, states: set) -> dict:\n",
    "    \"\"\"Ask `name`: are you `id`? and return mapping of answers to possible states.\"\"\"\n",
    "    groups = {word: set() for word in WORDS}\n",
    "    for state in states:\n",
    "        identity = IDS[state.names.index(name)]\n",
    "        truth = identity == id\n",
    "        words = sorted(WORDS, key=state.yes.__eq__)\n",
    "        if identity in (True, None):\n",
    "            groups[words[truth]].add(state)\n",
    "        if identity in (False, None):\n",
    "            groups[words[not truth]].add(state)\n",
    "    return groups\n",
    "\n",
    "ask('A', None, STATES)"
   ],
   "cell_type": "code",
   "metadata": {},
   "execution_count": 3,
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "{'da': {State(names='ABC', yes='da'),\n",
       "  State(names='ACB', yes='da'),\n",
       "  State(names='BAC', yes='ja'),\n",
       "  State(names='BCA', yes='da'),\n",
       "  State(names='BCA', yes='ja'),\n",
       "  State(names='CAB', yes='ja'),\n",
       "  State(names='CBA', yes='da'),\n",
       "  State(names='CBA', yes='ja')},\n",
       " 'ja': {State(names='ABC', yes='ja'),\n",
       "  State(names='ACB', yes='ja'),\n",
       "  State(names='BAC', yes='da'),\n",
       "  State(names='BCA', yes='da'),\n",
       "  State(names='BCA', yes='ja'),\n",
       "  State(names='CAB', yes='da'),\n",
       "  State(names='CBA', yes='da'),\n",
       "  State(names='CBA', yes='ja')}}"
      ]
     },
     "metadata": {},
     "execution_count": 3
    }
   ]
  },
  {
   "source": [
    "To determine if a question is making progress, we need to look at the set of names returned for each answer. A valid solution would need to output sets of at most size $2^2 = 4$ on the first question in order to proceed."
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "False {'BAC', 'CBA', 'CAB', 'ABC', 'ACB', 'BCA'} {'CAB', 'CBA', 'BAC', 'ABC', 'ACB', 'BCA'}\nTrue {'CAB', 'CBA', 'BAC', 'ABC', 'ACB', 'BCA'} {'BAC', 'CBA', 'CAB', 'ABC', 'ACB', 'BCA'}\nNone {'BAC', 'CBA', 'CAB', 'ABC', 'ACB', 'BCA'} {'CAB', 'CBA', 'BAC', 'ABC', 'ACB', 'BCA'}\n"
     ]
    }
   ],
   "source": [
    "for id in IDS:\n",
    "    groups = ask('A', id, STATES)\n",
    "    identities = [{names for names, _ in group} for group in groups.values()]\n",
    "    print(id, *identities)"
   ]
  },
  {
   "source": [
    "So that question made no progress. Unsurprising given that we don't know which god is \"Random\". Here one could resort to heuristics and increasingly convoluted questions.\n",
    "\n",
    "Let's do the opposite: write the most general question possible and automate the search. Any question can be modeled by asking whether any of a given set of states is accurate."
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "{'da': {State(names='ABC', yes='ja'),\n",
       "  State(names='ACB', yes='ja'),\n",
       "  State(names='BAC', yes='da'),\n",
       "  State(names='BCA', yes='da'),\n",
       "  State(names='BCA', yes='ja'),\n",
       "  State(names='CAB', yes='ja'),\n",
       "  State(names='CBA', yes='da'),\n",
       "  State(names='CBA', yes='ja')},\n",
       " 'ja': {State(names='ABC', yes='da'),\n",
       "  State(names='ACB', yes='da'),\n",
       "  State(names='BAC', yes='ja'),\n",
       "  State(names='BCA', yes='da'),\n",
       "  State(names='BCA', yes='ja'),\n",
       "  State(names='CAB', yes='da'),\n",
       "  State(names='CBA', yes='da'),\n",
       "  State(names='CBA', yes='ja')}}"
      ]
     },
     "metadata": {},
     "execution_count": 5
    }
   ],
   "source": [
    "def ask(name: str, include: set, exclude: set) -> dict:\n",
    "    \"\"\"Ask `name`: are we in any of `include` states? and return mapping of answers to possible states.\"\"\"\n",
    "    assert include.isdisjoint(exclude)\n",
    "    groups = {word: set() for word in WORDS}\n",
    "    for state in include | exclude:\n",
    "        identity = IDS[state.names.index(name)]\n",
    "        truth = state in include\n",
    "        words = sorted(WORDS, key=state.yes.__eq__)\n",
    "        if identity in (True, None):\n",
    "            groups[words[truth]].add(state)\n",
    "        if identity in (False, None):\n",
    "            groups[words[not truth]].add(state)\n",
    "    return groups\n",
    "\n",
    "include = set(STATES[:len(STATES) // 2])\n",
    "ask('A', include, set(STATES) - include)        "
   ]
  },
  {
   "source": [
    "With that, the [power set](https://en.wikipedia.org/wiki/Power_set) of all possible combinations can be searched."
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "96"
      ]
     },
     "metadata": {},
     "execution_count": 6
    }
   ],
   "source": [
    "def powerset(states: set):\n",
    "    \"\"\"Generate all possible subsets.\"\"\"\n",
    "    for r in range(len(states) + 1):\n",
    "        yield from map(set, itertools.combinations(states, r))\n",
    "\n",
    "count = 0\n",
    "for states in powerset(STATES):\n",
    "    groups = ask('A', states, set(STATES) - states)\n",
    "    identities = [{names for names, _ in group} for group in groups.values()]\n",
    "    count += max(map(len, identities)) <= 4\n",
    "count"
   ]
  },
  {
   "source": [
    "So there are many potential solutions. Onto automating the search."
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "'ABC'"
      ]
     },
     "metadata": {},
     "execution_count": 7
    }
   ],
   "source": [
    "def search(states: set, count: int = 3):\n",
    "    \"\"\"Recursively ask all possible questions until a solution is found.\"\"\"\n",
    "    identities = {names for names, _ in states}\n",
    "    if len(identities) == 1:  # solved\n",
    "        return identities.pop()\n",
    "    if not count or len(identities) > (2 ** count):  # impossible\n",
    "        return None\n",
    "    for name, subset in itertools.product(NAMES, powerset(states)):\n",
    "        groups = ask(name, subset, states - subset)\n",
    "        solutions = [search(group, count - 1) for group in groups.values()]\n",
    "        if all(solutions):\n",
    "            return name, subset, solutions\n",
    "\n",
    "search(set(STATES[:2]), 0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "('A',\n",
       " {State(names='ABC', yes='da'), State(names='ACB', yes='ja')},\n",
       " ['ACB', 'ABC'])"
      ]
     },
     "metadata": {},
     "execution_count": 8
    }
   ],
   "source": [
    "search(set(STATES[:4]), 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "('A',\n",
       " {State(names='ABC', yes='da'), State(names='ACB', yes='ja')},\n",
       " [('A', {State(names='ACB', yes='da')}, ['BAC', 'ACB']),\n",
       "  ('A', {State(names='ABC', yes='ja')}, ['ABC', 'BAC'])])"
      ]
     },
     "metadata": {},
     "execution_count": 9
    }
   ],
   "source": [
    "search(set(STATES[:6]), 2)"
   ]
  },
  {
   "source": [
    "So far, so good. The output is binary tree specifying the addressed god and the states asked about at each node.\n",
    "\n",
    "The sub-problems are solving a sufficient number of cases. It's no surpise that there should be solutions asking \"A\" first since it can't matter who gets the first question. Now for the real solution."
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "CPU times: user 1.29 s, sys: 10.8 ms, total: 1.3 s\nWall time: 1.3 s\n"
     ]
    },
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "('A',\n",
       " {State(names='ABC', yes='da'),\n",
       "  State(names='ACB', yes='ja'),\n",
       "  State(names='BAC', yes='ja'),\n",
       "  State(names='CAB', yes='da')},\n",
       " [('C',\n",
       "   {State(names='ACB', yes='ja'),\n",
       "    State(names='BCA', yes='da'),\n",
       "    State(names='CAB', yes='da'),\n",
       "    State(names='CBA', yes='ja')},\n",
       "   [('B',\n",
       "     {State(names='BCA', yes='ja'), State(names='CBA', yes='ja')},\n",
       "     ['BCA', 'CBA']),\n",
       "    ('A',\n",
       "     {State(names='ACB', yes='da'), State(names='CAB', yes='da')},\n",
       "     ['CAB', 'ACB'])]),\n",
       "  ('B',\n",
       "   {State(names='ABC', yes='da'),\n",
       "    State(names='BAC', yes='da'),\n",
       "    State(names='BCA', yes='ja'),\n",
       "    State(names='CBA', yes='ja')},\n",
       "   [('B',\n",
       "     {State(names='ABC', yes='da'), State(names='BCA', yes='da')},\n",
       "     ['ABC', 'BCA']),\n",
       "    ('B',\n",
       "     {State(names='BAC', yes='ja'), State(names='CBA', yes='ja')},\n",
       "     ['BAC', 'CBA'])])])"
      ]
     },
     "metadata": {},
     "execution_count": 10
    }
   ],
   "source": [
    "%time search(set(STATES))"
   ]
  },
  {
   "source": [
    "The puzzle is solved. Can it be simplified? Depends on your point of view.\n",
    "\n",
    "[Canonical solutions](https://en.wikipedia.org/wiki/The_Hardest_Logic_Puzzle_Ever#The_solution) introduce [biconditionals](https://en.wikipedia.org/wiki/Logical_biconditional) or [conterfactuals](https://en.wikipedia.org/wiki/Counterfactual_conditional) in an attempt to collapse the output possibilities. This is ultimately hopeless though, as the solution is a binary search tree regardless. Is asking a question of the form \"If I asked you ..., would just say ja\" actually clearer than asking \"Are we in any of these possibilities: ...\"?\n",
    "\n",
    "Nonetheless patterns do emerge:\n",
    "* The first question revolves around ruling out \"Random\".\n",
    "* Subsequent questions address non-\"Random\" gods.\n",
    "\n",
    "The random behavior adds true complexity to the algorithm, whereas the the boolean encoding adds arbitrary complications."
   ],
   "cell_type": "markdown",
   "metadata": {}
  }
 ],
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3",
   "language": "python"
  },
  "nikola": {
   "category": "puzzles",
   "date": "2021-01-01",
   "description": "",
   "link": "",
   "slug": "hardest-logic-puzzle-ever",
   "tags": "",
   "title": "Hardest Logic Puzzle Ever",
   "type": "text"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}